<?php
require_once '../config/database.php';
require_once '../includes/operation_logger.php';

// JSON 响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'list':
                try {
                    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
                    $limit = isset($_GET['limit']) ? max(1, min(100, intval($_GET['limit']))) : 20;
                    $offset = ($page - 1) * $limit;
                    
                    $whereClause = '';
                    $params = [];
                    
                    // 状态筛选
                    if (!empty($_GET['status'])) {
                        $whereClause .= " AND tr.status = ?";
                        $params[] = $_GET['status'];
                    }
                    
                    // 日期筛选
                    if (!empty($_GET['date'])) {
                        $whereClause .= " AND tr.reservation_date = ?";
                        $params[] = $_GET['date'];
                    }
                    
                    // 搜索关键词
                    if (!empty($_GET['keyword'])) {
                        $keyword = '%' . $_GET['keyword'] . '%';
                        $whereClause .= " AND (tr.team_name LIKE ? OR tr.contact_name LIKE ? OR tr.contact_unit LIKE ? OR tr.contact_phone LIKE ?)";
                        $params = array_merge($params, [$keyword, $keyword, $keyword, $keyword]);
                    }
                    
                    // 获取总数
                    $countSql = "SELECT COUNT(*) FROM team_reservations tr WHERE 1=1 $whereClause";
                    $countStmt = $pdo->prepare($countSql);
                    $countStmt->execute($params);
                    $total = $countStmt->fetchColumn();
                    
                    // 获取数据
                    $sql = "SELECT 
                        tr.*,
                        au.username as approved_by_name
                    FROM team_reservations tr 
                    LEFT JOIN admin_users au ON tr.approved_by = au.id 
                    WHERE 1=1 $whereClause 
                    ORDER BY tr.created_at DESC 
                    LIMIT $limit OFFSET $offset";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $reservations = $stmt->fetchAll();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => [
                            'list' => $reservations,
                            'pagination' => [
                                'page' => $page,
                                'limit' => $limit,
                                'total' => intval($total),
                                'pages' => ceil($total / $limit)
                            ]
                        ]
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取团队预约列表失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'detail':
                try {
                    if (empty($_GET['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少预约ID',
                            'data' => null
                        ]);
                    }
                    
                    $sql = "SELECT 
                        tr.*,
                        au.username as approved_by_name,
                        u.nickname as user_nickname,
                        u.real_name as user_real_name
                    FROM team_reservations tr 
                    LEFT JOIN admin_users au ON tr.approved_by = au.id 
                    LEFT JOIN users u ON tr.user_id = u.id 
                    WHERE tr.id = ?";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$_GET['id']]);
                    $reservation = $stmt->fetch();
                    
                    if (!$reservation) {
                        sendJson([
                            'code' => 404,
                            'message' => '团队预约不存在',
                            'data' => null
                        ]);
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $reservation
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取团队预约详情失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'create':
                try {
                    // 验证必要字段
                    $required = ['team_name', 'visitor_identity', 'contact_name', 'contact_unit', 'contact_phone', 'reservation_date', 'reservation_time', 'visitor_count'];
                    foreach ($required as $field) {
                        if (empty($input[$field])) {
                            sendJson([
                                'code' => 400,
                                'message' => "缺少必要字段: $field",
                                'data' => null
                            ]);
                        }
                    }
                    
                    // 验证手机号格式
                    if (!preg_match('/^1[3-9]\d{9}$/', $input['contact_phone'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '手机号格式不正确',
                            'data' => null
                        ]);
                    }
                    
                    // 验证日期格式
                    if (!strtotime($input['reservation_date'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '预约日期格式不正确',
                            'data' => null
                        ]);
                    }
                    
                    // 验证时间格式
                    if (!preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $input['reservation_time'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '预约时间格式不正确',
                            'data' => null
                        ]);
                    }
                    
                    $sql = "INSERT INTO team_reservations (
                        team_name, visitor_identity, contact_name, contact_unit, contact_phone,
                        visitor_info, need_guide, reservation_date, reservation_time, end_time,
                        visitor_count, user_id, status, created_at, updated_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
                    
                    $params = [
                        $input['team_name'],
                        $input['visitor_identity'],
                        $input['contact_name'],
                        $input['contact_unit'],
                        $input['contact_phone'],
                        $input['visitor_info'] ?? '',
                        isset($input['need_guide']) ? intval($input['need_guide']) : 0,
                        $input['reservation_date'],
                        $input['reservation_time'],
                        $input['end_time'] ?? null,
                        intval($input['visitor_count']),
                        $input['user_id'] ?? null,
                        $input['status'] ?? 'pending'
                    ];
                    
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result) {
                        $reservationId = $pdo->lastInsertId();
                        
                        // 记录操作日志
                        $currentAdmin = getCurrentAdmin($pdo);
                        if ($currentAdmin) {
                            logAdminOperation(
                                $pdo,
                                $currentAdmin[0],
                                $currentAdmin[1],
                                '团队预约创建',
                                'team_reservations',
                                "创建团队预约：{$input['team_name']}，联系人：{$input['contact_name']}",
                                ['reservation_id' => $reservationId, 'team_name' => $input['team_name']]
                            );
                        }
                        
                        sendJson([
                            'code' => 200,
                            'message' => '创建团队预约成功',
                            'data' => ['id' => $reservationId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '创建团队预约失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '创建团队预约失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'update_status':
                try {
                    if (empty($input['id']) || empty($input['status'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少必要参数',
                            'data' => null
                        ]);
                    }
                    
                    $allowedStatuses = ['pending', 'approved', 'rejected', 'cancelled', 'completed'];
                    if (!in_array($input['status'], $allowedStatuses)) {
                        sendJson([
                            'code' => 400,
                            'message' => '无效的状态值',
                            'data' => null
                        ]);
                    }
                    
                    // 获取当前管理员信息
                    $currentAdmin = getCurrentAdmin($pdo);
                    if (!$currentAdmin) {
                        sendJson([
                            'code' => 401,
                            'message' => '未找到管理员信息',
                            'data' => null
                        ]);
                    }
                    
                    // 获取原始数据
                    $stmt = $pdo->prepare("SELECT team_name, contact_name, status FROM team_reservations WHERE id = ?");
                    $stmt->execute([$input['id']]);
                    $original = $stmt->fetch();
                    
                    if (!$original) {
                        sendJson([
                            'code' => 404,
                            'message' => '团队预约不存在',
                            'data' => null
                        ]);
                    }
                    
                    $sql = "UPDATE team_reservations SET 
                        status = ?, 
                        admin_notes = ?, 
                        approved_by = ?, 
                        approved_at = NOW(), 
                        updated_at = NOW() 
                        WHERE id = ?";
                    
                    $params = [
                        $input['status'],
                        $input['admin_notes'] ?? '',
                        $currentAdmin[0],
                        $input['id']
                    ];
                    
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result) {
                        // 状态映射
                        $statusMap = [
                            'pending' => '待审核',
                            'approved' => '已批准',
                            'rejected' => '已拒绝',
                            'cancelled' => '已取消',
                            'completed' => '已完成'
                        ];
                        
                        $statusText = $statusMap[$input['status']] ?? $input['status'];
                        $adminNotes = !empty($input['admin_notes']) ? "，备注：{$input['admin_notes']}" : '';
                        
                        // 记录操作日志
                        logAdminOperation(
                            $pdo,
                            $currentAdmin[0],
                            $currentAdmin[1],
                            '团队预约状态变更',
                            'team_reservations',
                            "将团队预约「{$original['team_name']}」状态更改为：{$statusText}{$adminNotes}",
                            ['reservation_id' => $input['id'], 'new_status' => $input['status'], 'admin_notes' => $input['admin_notes'] ?? '']
                        );
                        
                        sendJson([
                            'code' => 200,
                            'message' => '更新状态成功',
                            'data' => null
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '更新状态失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新状态失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'update':
                try {
                    if (empty($input['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少预约ID',
                            'data' => null
                        ]);
                    }
                    
                    // 验证必要字段
                    $required = ['team_name', 'visitor_identity', 'contact_name', 'contact_unit', 'contact_phone', 'reservation_date', 'reservation_time', 'visitor_count'];
                    foreach ($required as $field) {
                        if (empty($input[$field])) {
                            sendJson([
                                'code' => 400,
                                'message' => "缺少必要字段: $field",
                                'data' => null
                            ]);
                        }
                    }
                    
                    $sql = "UPDATE team_reservations SET 
                        team_name = ?, visitor_identity = ?, contact_name = ?, 
                        contact_unit = ?, contact_phone = ?, visitor_info = ?, 
                        need_guide = ?, reservation_date = ?, reservation_time = ?, 
                        end_time = ?, visitor_count = ?, updated_at = NOW() 
                        WHERE id = ?";
                    
                    $params = [
                        $input['team_name'],
                        $input['visitor_identity'],
                        $input['contact_name'],
                        $input['contact_unit'],
                        $input['contact_phone'],
                        $input['visitor_info'] ?? '',
                        isset($input['need_guide']) ? intval($input['need_guide']) : 0,
                        $input['reservation_date'],
                        $input['reservation_time'],
                        $input['end_time'] ?? null,
                        intval($input['visitor_count']),
                        $input['id']
                    ];
                    
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result) {
                        // 记录操作日志
                        $currentAdmin = getCurrentAdmin($pdo);
                        if ($currentAdmin) {
                            logAdminOperation(
                                $pdo,
                                $currentAdmin[0],
                                $currentAdmin[1],
                                '团队预约修改',
                                'team_reservations',
                                "修改团队预约：{$input['team_name']}，联系人：{$input['contact_name']}",
                                ['reservation_id' => $input['id'], 'team_name' => $input['team_name']]
                            );
                        }
                        
                        sendJson([
                            'code' => 200,
                            'message' => '更新团队预约成功',
                            'data' => null
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '更新团队预约失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新团队预约失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'DELETE':
        if ($action == 'delete') {
            try {
                if (empty($_GET['id'])) {
                    sendJson([
                        'code' => 400,
                        'message' => '缺少预约ID',
                        'data' => null
                    ]);
                }
                
                // 获取原始数据
                $stmt = $pdo->prepare("SELECT team_name, contact_name FROM team_reservations WHERE id = ?");
                $stmt->execute([$_GET['id']]);
                $original = $stmt->fetch();
                
                if (!$original) {
                    sendJson([
                        'code' => 404,
                        'message' => '团队预约不存在',
                        'data' => null
                    ]);
                }
                
                $stmt = $pdo->prepare("DELETE FROM team_reservations WHERE id = ?");
                $result = $stmt->execute([$_GET['id']]);
                
                if ($result) {
                    // 记录操作日志
                    $currentAdmin = getCurrentAdmin($pdo);
                    if ($currentAdmin) {
                        logAdminOperation(
                            $pdo,
                            $currentAdmin[0],
                            $currentAdmin[1],
                            '团队预约删除',
                            'team_reservations',
                            "删除团队预约：{$original['team_name']}，联系人：{$original['contact_name']}",
                            ['reservation_id' => $_GET['id'], 'team_name' => $original['team_name']]
                        );
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '删除团队预约成功',
                        'data' => null
                    ]);
                } else {
                    sendJson([
                        'code' => 500,
                        'message' => '删除团队预约失败',
                        'data' => null
                    ]);
                }
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '删除团队预约失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>